package com.doyoulearn.socket.基于TCPIP的Socket通信;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 维护长连接：消耗内存
 */
public class TcpSocketServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket(10124);
        System.out.println("等待连接");
        Socket client = serverSocket.accept();
        System.out.println("连接成功！");
        while (true) {
            Thread.sleep(1000);
            client.getOutputStream().write(hex2ByteArray("7EFF060F000101EF"));
            System.err.println("发送成功");
        }
    }

    private static byte[] hex2ByteArray(String inHex) {

        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            hexlen++;
            result = new byte[hexlen / 2];
            inHex = "0" + inHex;
        } else {
            result = new byte[hexlen / 2];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i+=2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    private static byte hexToByte(String inHex) {
        return (byte)Integer.parseInt(inHex, 16);
    }
}
